package com.lagou.sqlSession;

import com.lagou.enumconfig.SqlTypeEnum;
import com.lagou.pojo.Configuration;
import com.lagou.utils.ParameterMapping;

import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }


    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用JDK动态代理为Dao接口生成代理对象并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(),new Class[]{mapperClass} , new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //proxy被代理的接口引用、被代理接口方法名引用、args方法参数
                //底层仍执行JDBC ，根据情况选择调用selectAll或seelctOne

                /**
                 * 1、准备参数：statementId（sql唯一标识符namespace。id）
                 * 由于invoke方法中无法获取相关配置信息，采用约定namespace.id = 接口全限定名.方法名的方式进行命名
                 */
                String methodName = method.getName(); //方法名
                String className = method.getDeclaringClass().getName(); //接口类全限定名

                String stateMentId = className+"."+methodName;
                /**
                 * 2、method所需参数及返回值类型判断
                 */
                Type genericReturnType = method.getGenericReturnType();

                SqlTypeEnum sqlTypeEnum = configuration.getMappedStatementMap().get(stateMentId).getSqlTypeEnum();

                Object result = null;
                switch (sqlTypeEnum){
                    case INSERT:
                    case UPDATE:
                    case DELETE:
                        result = update(stateMentId,args);
                        break;
                    case SELECT:
                        //判断 是否进行了 泛型类型参数化
                        if(genericReturnType instanceof ParameterizedType){
                            List<Object> objects = selectAll(stateMentId, args);
                            result = objects;
                        }else{
                            result = selectOne(stateMentId,args);
                        }
                        break;

                    default:
                        break;
                }

                return result;
            }
        });
        return (T) proxyInstance;
    }

    @Override
    public <E> List<E> selectAll(String statementId, Object... params) throws Exception {
        //调用simpleExecutor里的query方法
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        List<Object> list = simpleExecutor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectAll(statementId, params);
        if(objects.size()==1){
            return (T) objects.get(0);
        }else{
            throw new RuntimeException("查询结果过多或为空");
        }
    }

/*    @Override
    public Integer insert(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        return simpleExecutor.insert(configuration,configuration.getMappedStatementMap().get(statementId),params);
    }

    @Override
    public Integer delete(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        return simpleExecutor.delete(configuration,configuration.getMappedStatementMap().get(statementId),params);
    }*/

    @Override
    public Integer update(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        return simpleExecutor.update(configuration,configuration.getMappedStatementMap().get(statementId),params);
    }
}
